﻿using MDIDemo.Model;
using MDIDemo.PublicClass;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xceed.Document.NET;
using Xceed.Words.NET;

namespace DevMy.PublicClass
{
    public class Class_WordOut
    {
        private Class_SQLiteOperator class_SQLiteOperator;
        public Class_WordOut()
        {
            class_SQLiteOperator = new Class_SQLiteOperator();
        }

        public string OutWord(string id, DocReplaceModel[] docReplaceModels)
        {
            if (docReplaceModels == null || docReplaceModels.Length == 0)
                return null;

            string allPathFileName = null;
            DocModel docModel = class_SQLiteOperator.GetDocModelOne(id);
            if (docModel == null)
                return null;
            string TempDocName = Application.StartupPath + "\\" + docModel.path + "\\" + docModel.docName;
            if (!File.Exists(TempDocName))
                return null;
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            try
            {

                saveFileDialog.Title = "导出";
                saveFileDialog.Filter = "Word 文档（*.docx）| *.docx";
                saveFileDialog.FileName = docModel.docName;
                saveFileDialog.RestoreDirectory = true;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    allPathFileName = saveFileDialog.FileName;
                    using (DocX document = DocX.Load(@TempDocName))
                    {
                        document.ReplaceText("｛", "{");
                        document.ReplaceText("｝", "}");
                        foreach (DocReplaceModel item in docReplaceModels)
                        {
                            if (item.oldInfomation != null && item.newInfomation != null)
                            {
                                //document.ReplaceText("{" + item.oldInfomation + "}"
                                //    , item.newInfomation
                                //    , false
                                //    , RegexOptions.IgnoreCase
                                //    , new Formatting() { Bold = true, FontColor = System.Drawing.Color.Blue });
                                document.ReplaceText("{" + item.oldInfomation + "}"
                                    , item.newInfomation);
                            }
                        }
                        document.SaveAs(allPathFileName);
                    }
                }
                saveFileDialog.Dispose();

                return allPathFileName;
            }
            catch (Exception e)
            {
                throw e;
            }

        }
    }
}
